/**
 * Created by 小敏哥on 2017/3/8.
 */
import React, {Component} from 'react';
import {Link} from 'react-router';
import {connect} from 'react-redux';
import {Toast, Popup} from 'antd-mobile';
import AlipayJSOperation from '../../utils/alipayJSOperation';
import style from './yearlyCheckDetail.scss';
import {checkInspection} from '../../actions/homeAction';
import PageBar from '../../components/common/pageBar';
import IconText  from '../../components/calculatorOfYearlyCheck/iconText';
import {MeansureAgain} from '../../components/Home';
import SendCxytjMessage from '../../utils/sendCxytjMessage';
import typeOfBrowser from '../../utils/typeOfBrowser';
import jsApi from '../../utils/cx580.jsApi';

class YearlyCheckDetail extends Component {
    constructor(props) {
        super(props);
        this.checkInspection = this.checkInspection.bind(this);
        this.goToComfirmOrder = this.goToComfirmOrder.bind(this);
        this.goBackToCalculator = this.goBackToCalculator.bind(this);
    }


    //当获取不到所需数据时直接定位到首页，由于首页做了一些兼容，不带userId
    dataEmptyErrorOperation() {
        if (!this.props.carNumber) {
            location.replace(`${location.href.split('?')[0].split('#')[0]}#/?userId=${localStorage.getItem('userId')}&detailUserType=${localStorage.getItem('detailUserType')}`);
        }
    }

    //检查车辆是否支持年检代办
    checkInspection(callBack) {
        this.props.dispatch(checkInspection({carNumber: this.props.carNumber, carId: this.props.carId}, (result) => {
            callBack(result);
        }))
    }

    //返回计算器
    goBackToCalculator() {
        history.back();
        SendCxytjMessage.sendMessage({eventId:'Insepection_Recalculate'});
    }

    //返回首页
    goHome(){
        /*if(navigator.userAgent.indexOf("appname_cxycwz") > -1) {
            //app新打开webview，故此处直接关闭webview回到首页
            jsApi.call(
                {
                    "commandId": "",
                    "command": "close"
                });
        }
        else {*/
            history.go(-2);
       /* }*/
    }


    //弹出定位提示
    showMeansure(continueCallBack) {
        let attrs = {
            city: this.props.position,
            cancel: () => {
                Popup.hide();
            },
            continue: () => {
                Popup.hide();
                continueCallBack();
            }
        };
        Popup.show(<MeansureAgain {...attrs}/>, {animationType: 'slide-up'});
    }

    //构建跳转地址
    getInspectionUrl(bizFlag) {
        let url='';
        if(typeOfBrowser.getChannelOfBrowser()=='app'){
            let finurl=encodeURIComponent(`/confirmOrder/${this.props.carId}/${encodeURIComponent(this.props.carNumber)}/${bizFlag}`);
            url=`remindProcessDetail/${finurl}`;
        }
        else{
            url=`/confirmOrder/${this.props.carId}/${encodeURIComponent(this.props.carNumber)}/${bizFlag}`;
        }
        return url;
    }


    toUrlByOpenNewView(url) {
        if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
            //此处增加app用于识别年检提醒
            let finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app&appType=remind/#${url}`;
            common.openNewBrowserWithURL(finalUrl);
        }
        else {
            this.context.router.push(url);
        }
    }

    //去往订单确认页
    goToComfirmOrder() {
        //首先根据后端返回的状态判断
        if (this.props.canCheck) {
            this.checkInspection((result) => {
                if (result.validateFlag) {
                    //7,9,10,10这几种状态监测到定位不在广州时弹出二次确认框
                    if (this.props.position && this.props.position.indexOf('广州') < 0 && (result.state == 7 || result.state == 9 || result.state == 10 || result.state == 11)) {
                        this.showMeansure(() => {
                            this.toUrlByOpenNewView(this.getInspectionUrl(result.bizFlag));
                        })
                    }
                    else {
                        //正常套路
                        this.toUrlByOpenNewView(this.getInspectionUrl(result.bizFlag));
                    }
                }
                else {
                    //验证不通过时弹窗
                    Toast.info(result.msg, 3);
                }
            })
        }
        SendCxytjMessage.sendMessage({eventId:'Insepection_Results_HandletheInsepection'});
    }


    componentWillMount() {
        this.dataEmptyErrorOperation();
    }

    componentDidMount() {
        //隐藏标题栏右键
        AlipayJSOperation.setRightButtonStatus(false);
        AlipayJSOperation.setTitle('年检状态');
        AlipayJSOperation.setBarColor('#2FB3FE');
        document.querySelector("title").innerHTML = "年检状态";
        SendCxytjMessage.sendMessage({eventId:'Insepection_EnterResults'});
    }

    componentWillUnmount() {
        AlipayJSOperation.removeLeftButtonEvent();
    }

    render() {
        let statusMap = {
            0: {
                message: `该车辆距年检预约还有${this.props.days}天，请放心驾驶。`
            },
            1: {
                message: `该车辆已进入年检办理周期，请您在年检有效期内办理年检（还剩余${this.props.days}天），否则车辆将面临扣分和有事故不能出险的风险！`
            }

        };
        let fontStyle = {
            color: this.props.color
        };
        return <div className={style.container}>
          {/*  <PageBar title="年检状态" />*/}
            <div className={style.titleGroup}>
                <IconText imgUrl="./images/carNumber.png" text={this.props.carNumber}/>
                <div className={style.goBack}><img src="./images/computeAgain_gray.png"/><Link
                    onClick={this.goBackToCalculator}>重新计算</Link></div>
            </div>
            <div className={style.warningDiv}><img src={this.props.imgUrl}/></div>
            <div style={fontStyle} className={style.warningText}>{this.props.status}</div>
            <div className={style.dateMessage}>
                <span>注册日期：</span><span>{this.props.registerDate}</span><span>检验有效期：</span><span>{this.props.expiryDate}</span>
            </div>
            <div className={style.content}>
                <div className={style.contentItem}>
                    <div className={style.bluePoint}></div>
                    <p>{this.props.statusMsg}</p></div>
                {this.props.status != '报废'&&this.props.nextType!='不可办理' ? <div className={style.contentItem}>
                        <div className={style.bluePoint}></div>
                        <p>本次年检类型：<span className={style.yearlyCheckType}>{this.props.nextType}</span></p></div> : ''}
            </div>
            {
                this.props.canCheck ? <div className={style.buttonGroup}>
                        <button onClick={this.goHome} className={style.goBackButton}>返回</button>
                        <button onClick={this.goToComfirmOrder} className={style.goToOrder}>立即办理</button>
                    </div> :
                    <div className={style.buttonGroup}>
                        <button onClick={this.goHome} className={style.goBackButton+' '+style.singleButton}>返回</button></div>
            }
        </div>
    }
}

//react router跳转时使用了context，此处需要显式声明
YearlyCheckDetail.contextTypes = {
    router: React.PropTypes.object.isRequired
};

function mapStateToProps(state) {
    console.log(state);
    return Object.assign({}, state.calculatorInfo.yearlyCheckInfo, {
        position: state.homeInfo.position,
    });
}


export default connect(mapStateToProps)(YearlyCheckDetail)